<?php

namespace app\admin\model;

use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;
use think\Model;

class User extends Model
{

    // 表名
    protected $name = 'user';
    public $prefix_new = 'fa_';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [

    ];

    public function getOriginData()
    {
        return $this->origin;
    }

    //
    public function getUser_idTextAttr($value, $data=[])
    {
        $nn=preg_split("/,/",$value);
        $s=array();
        for($i=0;$i<count($nn);$i++) {
            if($nn[$i]=="") continue;
            $r = Model("User")->get(array("id" => $nn[$i]));
            if($r) $s[]= $r['username'];
        }
        return join(",",$s);
    }

    public function getTeacher_idTextAttr($value, $data=[])
    {
        $nn=preg_split("/,/",$value);
        $s=array();
        for($i=0;$i<count($nn);$i++) {
            if($nn[$i]=="") continue;
            $r = Model("User")->get(array("id" => $nn[$i]));
            if($r) $s[]= $r['username'];
        }
        return join(",",$s);
    }

    public function getstudent_idTextAttr($value, $data=[])
    {
        $nn=preg_split("/,/",$value);
        $s=array();
        for($i=0;$i<count($nn);$i++) {
            if($nn[$i]=="") continue;
            $r = Model("User")->get(array("id" => $nn[$i]));
            if($r) $s[]= $r['username'];
        }
        return join(",",$s);
    }


    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            //如果有修改密码
            if (isset($changed['password'])) {
                if ($changed['password']) {
                    $salt = \fast\Random::alnum();
                    $row->password = \app\common\library\Auth::instance()->getEncryptPassword($changed['password'], $salt);
                    $row->salt = $salt;
                } else {
                    unset($row->password);
                }
            }
        });


        self::beforeUpdate(function ($row) {
            $changedata = $row->getChangedData();
            $origin = $row->getOriginData();
            if (isset($changedata['money']) && (function_exists('bccomp') ? bccomp($changedata['money'], $origin['money'], 2) !== 0 : (double)$changedata['money'] !== (double)$origin['money'])) {
                MoneyLog::create(['user_id' => $row['id'], 'money' => $changedata['money'] - $origin['money'], 'before' => $origin['money'], 'after' => $changedata['money'], 'memo' => '管理员变更金额']);
            }
            if (isset($changedata['score']) && (int)$changedata['score'] !== (int)$origin['score']) {
                ScoreLog::create(['user_id' => $row['id'], 'score' => $changedata['score'] - $origin['score'], 'before' => $origin['score'], 'after' => $changedata['score'], 'memo' => '管理员变更积分']);
            }
        });
    }

    public function getGenderList()
    {
        return ['1' => __('Male'), '0' => __('Female')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    public function getPrevtimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['prevtime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getLogintimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['logintime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getJointimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['jointime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPrevtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setLogintimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setJointimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setBirthdayAttr($value)
    {
        return $value ? $value : null;
    }

    public function group()
    {
        return $this->belongsTo('UserGroup', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function getGenderTextAttr($value, $data=array())
    {
        $s=array();
        $content=array(
            "1"=>"男",
            "2"=>"女",
            );
        $nn=preg_split("/,/",$value);
        for($i=0;$i<count($nn);$i++) {
            if($nn[$i]=="") continue;
            if(isset($content[$nn[$i]])) $s[]= $content[$nn[$i]];
        }
        return join(",",$s);
    }

    public function getGroup_idTextAttr($value, $data=array())
    {
        $s=array();
        $content=array(
            "1"=>"学生",
            "2"=>"都是",
            "3"=>"管理员",
            "4"=>"领导",
            "5"=>"观察员",
            );
        $nn=preg_split("/,/",$value);
        for($i=0;$i<count($nn);$i++) {
            if($nn[$i]=="") continue;
            if(isset($content[$nn[$i]])) $s[]= $content[$nn[$i]];
        }
        return join(",",$s);
    }

    public static function setApiToken($user, $expireTime = 3600) {
        $issuedAt = time();
        $student=model("\app\admin\model\Student")->where("student_id",$user["id"])->order("id desc")->find();
        $expirationTime = $issuedAt + $expireTime;
        $payload = array(
            'iat' => $issuedAt,
            'exp' => $expirationTime,
            'uid' => $user["id"],
            'oid' => $user["openid"],
            'username' => $user["username"],
            'group_id' => $user["group_id"],
            'classes_id' => $student["classes_id"],
            'school_id' => $student["school_id"],
        );
        $token=JWT::encode($payload, "159456token!@#", 'HS256');
        header("Authorization: Bearer " . $token);
        return $token;
    }

    public static function getApiToken($token) {
        try {
            $token = str_replace('Bearer ', '', $token);
            $decoded = JWT::decode($token, new Key("159456token!@#", 'HS256'));
            return (array) $decoded;
        } catch (ExpiredException $e) {
             \app\common\controller\Api::errinfo('authorization 验证串无效或已过期');
        } catch (SignatureInvalidException $e) {
            \app\common\controller\Api::errinfo('authorization 验证串无效');
        } catch (BeforeValidException $e) {
            \app\common\controller\Api::errinfo('authorization 验证串无效');
        } catch (Exception $e) {
            \app\common\controller\Api::errinfo('authorization 验证串无效');
        }
        \app\common\controller\Api::errinfo('authorization 验证串无效');
        return false;
    }

}
